package com.ws.core.advice;


import com.alibaba.fastjson.JSONObject;
import com.ws.common.util.ResponseResult;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@Order(1000)
@ControllerAdvice(basePackages = "com.ws")
public class ResponseResultAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (null != body) {
            if (body instanceof String  ) {
                String bodyStr = (String) body;
                if (bodyStr.contains("\"code\":") && bodyStr.contains("\"msg\":")) {
                    return body;
                }
                return new ResponseResult(body).toString();
            }
            //已经是返回标准不再封装
            if (body instanceof ResponseResult) {
                return body;
            }
            String  returnStr = JSONObject.toJSONString(body);
            if (returnStr.contains("\"code\":") && returnStr.contains("\"msg\":")) {
                return body;
            }
        }
        return  new ResponseResult(body);
    }


}
